package com.itao.satoken.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaFoxUtil;
import cn.dev33.satoken.util.SaResult;
import com.itao.satoken.entity.LoginUser;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    // 测试登录，浏览器访问： http://localhost:8081/user/doLogin?username=zhang&password=123456
    @GetMapping("/doLogin")
    public SaResult doLogin(String username, String password, HttpServletRequest request) {
        var system = request.getHeader("system");
        if (SaFoxUtil.isEmpty(system)) {
            throw new IllegalStateException("system请求头为空");
        }
        // 此处仅作模拟示例，真实项目需要从数据库中查询数据进行比对 
        if("zhang".equals(username) && "123456".equals(password)) {
            // StpPcUtil.login(10001);
            // StpAppUtil.login(10001);
            StpUtil.login(10001, system);
            LoginUser loginUser = new LoginUser();
            loginUser.setUserName("sjt");
            loginUser.setId(StpUtil.getLoginIdAsLong());
            loginUser.setToken(StpUtil.getTokenValue());
            loginUser.setDeptId(123L);
            loginUser.setDeptName("研发部");
            loginUser.setSystem(system);
            StpUtil.getTokenSession().set("userInfo", loginUser);
            return SaResult.data(loginUser);
        }
        throw new RuntimeException("登录失败");
    }

    // 获取登录用户信息，浏览器访问： http://localhost:8081/user/getUserInfo
    @SaCheckLogin
    @GetMapping("/getUserInfo")
    public SaResult getUserInfo() {
        SaSession tokenSession = StpUtil.getTokenSession();
        LoginUser userInfo = (LoginUser) tokenSession.get("userInfo");
        return SaResult.data(userInfo);
    }

    // 查询登录状态，浏览器访问： http://localhost:8081/user/isLogin
    @GetMapping("/isLogin")
    public String isLogin() {
        return "当前会话是否登录：" + StpUtil.isLogin();
    }


    // 查询 Token 信息  ---- http://localhost:8081/user/tokenInfo
    @GetMapping("/tokenInfo")
    public SaResult tokenInfo() {
        return SaResult.data(StpUtil.getTokenInfo());
    }

    // 测试注销  ---- http://localhost:8081/user/logout
    @GetMapping("/logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok();
    }

    // 续期  ---- http://localhost:8081/user/renew
    @GetMapping("/renew")
    public SaResult renew() {
        StpUtil.renewTimeout(3600);
        return SaResult.ok();
    }

    // tokenSession  ---- http://localhost:8081/user/token/session
    @GetMapping("/token/session")
    public SaResult tokenSession() {
        SaSession tokenSession = StpUtil.getTokenSession();
        return SaResult.data(tokenSession);
    }
}
